import {
  WebSocketGateway,
  SubscribeMessage,
  ConnectedSocket,
  MessageBody,
  OnGatewayConnection,
  OnGatewayInit,
} from "@nestjs/websockets";
import { Server, Socket } from "socket.io";
import * as jwt from "jsonwebtoken";
@WebSocketGateway({ cors: true })
export class ChatGateway implements OnGatewayConnection, OnGatewayInit {
  server: Server;
  afterInit(server: Server) {
    this.server = server;
  }
  handleConnection(client: Socket) {
    try {
      const token =
        client.handshake.auth?.token ||
        (client.handshake.query && client.handshake.query.token);
      if (!token) {
        client.disconnect(true);
        return;
      }
      const payload: any = jwt.verify(
        token as string,
        process.env.JWT_SECRET || "secret"
      );
      (client as any).userId = payload.sub;
      client.join(`u:${payload.sub}`);
    } catch (e) {
      client.disconnect(true);
    }
  }
  @SubscribeMessage("chat:send") handleSend(
    @ConnectedSocket() client: Socket,
    @MessageBody() body: any
  ) {
    this.server
      .to(body.conversationId)
      .emit("chat:message", {
        id: "tmp-" + Date.now(),
        content: body.content,
        senderId: (client as any).userId,
        createdAt: new Date().toISOString(),
        conversation: { id: body.conversationId },
      });
    return { ok: true };
  }
  @SubscribeMessage("chat:join") handleJoin(
    @ConnectedSocket() client: Socket,
    @MessageBody() body: any
  ) {
    client.join(body.conversationId);
    return { ok: true };
  }
}
